<?php
require_once('inc/init.php');
require_once('inc/editor/ubb.php');
require_once getCacheFilePath('forums.php');
$hasImgAttach=false;
$hasCommonAttach=false;

if(!isLogin()){
	_header_("location:login.php?ref=".urlencode($_SERVER["REQUEST_URI"]) );
}

$userrow = $db->row_select_one("users", "id={$lg['userid']}");


$tid=numFilter($_GET['tid']);
$postid=numFilter($_GET['postid']);
$userid=0;
$cmdtitle="发布帖子";

if($postid>0){
	$row=$db->row_select_one("posts","id={$postid}");
	$fid=$row['fid'];
	$tid=$row['tid'];
}elseif($tid>0){
	$row=$db->row_select_one("topics","id={$tid}");
	$fid=$row['fid'];
}else{
	$fid=numFilter($_GET['fid']);
}


$forum=$cache_forums[$fid];

if(empty($forum)){
	printMsg('system_noforum');
}
if(intval($forum['pid'])==0){
	_header_("location:index.php?fid={$cache_forum['id']}");
}

if(!empty($forum['forumusers']) && !in_array($lg['username'],explode("\n",$forum['forumusers'])) && !isForumAdmin($fid)){
	printMsg('forum_forumusers');
}

if(!empty($forum['forumgroups']) && !in_array($lg['groupid'],explode(",",$forum['forumgroups'])) && !isForumAdmin($fid)){
	printMsg('forum_forumgroups');
}

if(!empty($forum['forumpass']) && getCookies("forumpass_{$fid}")!=$forum['forumpass'] && !isForumAdmin($fid)){
	printMsg('forum_forumpass');
}

//检测注册冻结时间
if($userrow['signuptime']>$_SYS['time']-$cache_settings['frozentime']*3600 && $lg['groupid']<200){
	printMsg('post_frozentime');
}
//检测发帖间隔时间
if($userrow['lastposttime']>$_SYS['time']-$cache_settings['postitime'] && $lg['groupid']<200){
	printMsg('post_postitime');
}



$action=strFilter($_GET['action']);
$topictype=numFilter($_GET['topictype']);
$title=strFilter($_POST['title']);
$title = trim(!empty($title) ? str_replace(array("\r", "\n", "\t"), array(' ', ' ', ' '), $title) : $title);
$content=trim(strFilter($_POST['content']));
$securitycode=strFilter($_POST['securitycode']);
$formaction="newtopic";
$action=($action==""? "topic": $action);
$oldpost=null;
$verifystr="";
$popedom_14=getPopedom(14);

switch($action){
	case "topic":
		$cmdtitle="发布主题";
		if($fid==0){printMsg('system_noforum');}
		$formaction="post.php?action=save&fid={$fid}&cmd={$action}&topictype={$topictype}";
		$verifystr=(numFilter($forum['isneedverify'])>0?"(需要审核)":"");
		if(getPopedom(9)==0){
			printMsg('popedom_9');
		}
		if($topictype==1 && getPopedom(6)==0){
			printMsg('popedom_6');
		}
		if($topictype==2 && getPopedom(7)==0){
			printMsg('popedom_7');
		}
			
	if($topictype==2){
		$rewardcredits = $cache_settings['rewardcredits'];
		if($rewardcredits=='user'){
			$creditsoption="<select name='rewardcredits' id='rewardcredits'>";
			foreach($cache_credits as $credits){
				$creditsoption.="<option value='{$credits['creditscode']}'>{$credits['creditsname']}</option>";
			}
			$creditsoption.="</select>";
		}else{
			$creditsoption="(".$cache_credits[$rewardcredits]['creditsname'].")";
		}
	}
	break;

	case "reply":
		$cmdtitle="回复帖子";
		if(getPopedom(10)==0){
			printMsg('popedom_10');
		}
		if($tid==0){printMsg('post_notopic');}
		$oldpost['title']="RE:".$row['title'];
		$quotepostid=numFilter($_GET['quotepostid']);
		if(!empty($quotepostid)){
			$quoterow=$db->row_select_one("posts","id={$quotepostid}");
			$oldpost['content']="[quote]".trim(cutStr($ubb->removeubb($quoterow['content']),30,true))."\n[color=#999999]".$quoterow['username']." 发表于 ".getDateStr($quoterow['posttime'],false,false)." [/color][/quote]\n\n[br/]";
		}
		$replypostid=numFilter($_GET['replypostid']);
		if(!empty($replypostid)){
			$p=numFilter($_GET['p']);
			$f=numFilter($_GET['f']);
			$replyrow=$db->row_select_one("posts","id={$replypostid}");
			$url=getUrlPath();
			$oldpost['content']="[color=#333333][b]回复 [url={$url}/view.php?tid={$tid}&page={$p}#f{$f}]#{$f}[/url] [i]{$replyrow['username']}[/i][/b][/color]\n\n[br/]";
		}

		$formaction="post.php?action=save&tid={$tid}&cmd={$action}&topictype={$topictype}";
		$verifystr=(numFilter($forum['isneedverify'])==2?"(需要审核)":"");
	break;

	case "edittopic":
		$cmdtitle="编辑主题";
		if($tid==0){printMsg('post_notopic');}
		$post_row=$db->row_select_one("posts","tid={$tid} and istopic=1");
		if($row[userid]!=$lg[userid] && !isForumAdmin($fid)){
			printMsg('post_ownererr');
		}
		if($row['islock']==1 && !isForumAdmin($fid)){
			printMsg('post_islock');
		}		
		$oldpost['title']=$post_row['title'];
		$oldpost['content']=$post_row['content'];
		$formaction="post.php?action=save&tid={$tid}&cmd={$action}&topictype={$topictype}";
		$verifystr=(numFilter($forum['isneedverify'])>0?"(需要审核)":"");		
	break;	

	case "editreply":
		$cmdtitle="编辑帖子";
		if($postid==0){printMsg('post_nopost');}
		$row=$db->row_select_one("posts","id={$postid} and istopic=0");
		if($row[userid]!=$lg[userid] && !isForumAdmin($fid)){
			printMsg('post_ownererr');
		}
		$oldpost['title']=$row['title'];
		$oldpost['content']=$row['content'];
		$formaction="post.php?action=save&postid={$postid}&cmd={$action}&topictype={$topictype}";
		$verifystr=(numFilter($forum['isneedverify'])==2?"(需要审核)":"");
	break;
}
$headtitle=$cmdtitle." - ".strip_tags($forum['forumname']);

if($action=="save"){
	$cmd=strFilter($_GET['cmd']);
	if(empty($content)){
		printMsg('post_required');
	}
	//验证码
	if($cache_settings['postsecuritycode']=='1' && strtolower($_SESSION['validationcode'])!=strtolower($securitycode)){
		printMsg('post_validationcodeerr');
	}
	switch($cmd){
		//新话题
		case "topic":
			if(empty($title)){
				printMsg('post_title_required');
			}
			
			if(getPopedom(9)==0){
				printMsg('popedom_9');
			}
			$timevar = time();

			$t1 = checkDirtyWords($title);
			$t2 = checkDirtyWords($content);
			
			if($t1['doaction']==2||$t2['doaction']==2){
				printMsg('post_failed_dirty');
			}
			
			$topic['title'] = $t1['content'];
			$topic['posttime'] = $topic['ordertime'] = $timevar;
			$topic['userid'] = $lg['userid'];
			$topic['username'] = $lg['username'];
			$topic['fid'] = $fid;
			$topic['topictype'] = $topictype;
			if(getPopedom(11)==1){
				$topic['verifystate']=1;
			}elseif(getPopedom(11)==2){
				$topic['verifystate']=0;
			}else{
				if(numFilter($forum['isneedverify'])>0 || $t1['doaction']==1 || $t2['doaction']==1){
					$topic['verifystate']=1;
				}
			}

			$topic['lastreply']= $timevar."\t".$lg['username'];
			$db->row_insert("topics",$topic);
			$tid=$db->insert_id();

			
			$post['title']=$t1['content'];
			$post['content'] = $t2['content'];
			$post['istopic']=1;
			$post['posttime'] = $timevar;
			$post['userid'] = $lg['userid'];
			$post['username'] = $lg['username'];
			$post['tid'] = $tid;
			$post['fid'] = $fid;
			$post['ip'] = getIP();
			$post['verifystate'] = (numFilter($forum['isneedverify'])>0?1:0);
			
			if(getPopedom(11)==1){
				$post['verifystate']=1;
			}elseif(getPopedom(11)==2){
				$post['verifystate']=0;
			}else{
				if(numFilter($forum['isneedverify'])>0 || $t1['doaction']==1 || $t2['doaction']==1){
					$post['verifystate']=1;
				}
			}			
			$db->row_insert("posts",$post);
			$postid = $db->insert_id();
			updateCredits($lg['userid'], 'postvar');
			checkAttachment($t2['content'], $tid, $postid);
			
			//发布投票
			if($topictype==1){
				if(getPopedom(6)==0){
					printMsg('popedom_6');
				}
				$voteitem=$_POST['voteitem'];
				$maxvotes=numFilter($_POST['maxvotes']);
				$starttime=$_POST['starttime'];
				$stoptime=$_POST['stoptime'];
				$viewresult=numFilter($_POST['viewresult']);
				$viewresult=($viewresult==0?0:1);
				$isopenvote=numFilter($_POST['isopenvote']);
				$isopenvote=($isopenvote==0?0:1);
	
				$voteitem = !empty($voteitem) ? str_replace("\t", ' ', $voteitem) : $voteitem;
				foreach($voteitem as $key=>$votei){
					$voteistr=trim($votei);
					if(empty($voteistr)){
						unset($voteitem[$key]);
					}else{
						$voteitem[$key] = $voteistr;
					}
				}
				if(count($voteitem)==0){
					printMsg('post_voteitemrequired');
				}
				if(count($voteitem)>10){
					printMsg('post_voteitemtoomuch');
				}
				$maxvotes=($maxvotes<1?1:$maxvotes);
				$maxvotes=($maxvotes>count($voteitem)?count($voteitem):$maxvotes);
				
				$starttime= empty($starttime) ? 0 : (strtotime($starttime)-$cache_settings['timeoffset']*3600);
				$stoptime= empty($stoptime) ? 0 :(strtotime($stoptime)+24*3600-$cache_settings['timeoffset']*3600-1);
				if($starttime && $stoptime && $stoptime>=$starttime){
				
				}else{
					printMsg('post_votetimeerr');
				}
				
				$vote['tid']= $tid;
				$vote['userid']= $lg['userid'];
				$vote['maxvotes'] = $maxvotes;
				$vote['starttime'] = $starttime;
				$vote['stoptime'] = $stoptime;
				$vote['viewresult']= $viewresult;
				$vote['isopenvote']= $isopenvote;
				$db->row_insert("votes",$vote);
				
				foreach($voteitem as $item){
					$v['tid']=$tid;
					$v['title']=$item;	
					$v['voteuids']='';
					$db->row_insert("voteitems",$v);
				}	
			}
			
			//发布悬赏
			if($topictype==2){
				if(getPopedom(7)==0){
					printMsg('popedom_7');
				}
				$availablecode = array('credits1', 'credits2', 'credits3', 'credits4', 'credits5', 'credits6', 'credits7', 'credits8');
				$rewardcredits=$_POST['rewardcredits'];
				$reward=numFilter($_POST['reward']);
				if(empty($rewardcredits)){
					$rewardcredits=$cache_settings['rewardcredits'];
				}elseif(!in_array($rewardcredits, $availablecode)){
					printMsg('post_creditserr');		//积分代码有错误
				}
				if($reward<1 || $reward>$userrow[$rewardcredits]){
					printMsg('post_rewarderr');		//积分数量有错误
				}
				$rewardobj['tid']=$tid;
				$rewardobj['userid']=$lg['userid'];
				$rewardobj['reward']=$reward;
				$rewardobj['rewardcredits']=$rewardcredits;
				$db->row_insert("reward", $rewardobj);
				//扣除用户积分
				$db->query_unbuffered("update `{$db->pre}users` set {$rewardcredits}={$rewardcredits}-{$reward} where id={$lg['userid']}");

			}
			
			//更新版块统计数量
			$db->query_unbuffered("update `{$db->pre}forums` set todaynum=todaynum+1,topicsnum=topicsnum+1,postsnum=postsnum+1,lasttid='{$tid}',lastuser='{$lg['username']}',lastpost='{$title}',lastposttime='{$timevar}' where id={$fid}");
			
			$db->query_unbuffered("update `{$db->pre}cache1` set todaynum=todaynum+1,topicsnum=topicsnum+1,postsnum=postsnum+1");
			
			//更新用户帖数
			$db->query_unbuffered("update `{$db->pre}users` set postsnum=postsnum+1,lastposttime='{$timevar}' where id={$lg['userid']}");
			
			if($t1['doaction']==1||$t2['doaction']==1){
				printMsg('post_succeed_dirty');
			}else{
				printMsg('post_succeed');
			}
		break;
		
		//新回复
		case "reply":
			if(getPopedom(10)==0){
				printMsg('popedom_10');
			}
			$timevar=time();
			$row=$db->row_select_one("topics","id={$tid}");
			if($row[islock]==1 && !isForumAdmin($fid)){
				printMsg('post_islock');
			}
			$post['title']=empty($title)?"RE:{$row['title']}":$title;
			$post['content'] = $content;
			$post['istopic']=0;
			$post['posttime'] = $timevar;
			$post['userid'] = $lg['userid'];
			$post['username'] = $lg['username'];
			$post['tid'] = $row['id'];
			$post['fid'] = $row['fid'];
			$post['ip'] = getIP();
			$post['verifystate'] = (numFilter($forum['isneedverify'])==2?1:0);

			$db->row_insert("posts",$post);
			$postid = $db->insert_id();
			
			checkAttachment($content, $tid, $postid);
			
			//更新最后回复
			$tmpobj['lastreply']=$timevar."\t".$lg['username'];
			$tmpobj['ordertime'] = $timevar;
			$tmpobj['replynum']=$row['replynum'] + 1;
			$db->row_update("topics",$tmpobj,"id={$tid}");
			
			$db->query_unbuffered("update `{$db->pre}cache1` set todaynum=todaynum+1,postsnum=postsnum+1");
			//更新用户帖数
			$db->query_unbuffered("update `{$db->pre}users` set postsnum=postsnum+1,lastposttime='{$timevar}' where id={$lg['userid']}");

			//更新版块统计数量
			$db->query_unbuffered("update `{$db->pre}forums` set todaynum=todaynum+1,postsnum=postsnum+1,lasttid='{$row['id']}',lastuser='{$lg['username']}',lastpost='{$post['title']}',lastposttime='{$timevar}' where id={$fid}");


			updateCredits($lg['userid'], 'replyvar');
			printMsg('post_replysucceed');
		break;
		
		//编辑话题
		case "edittopic":
			if(empty($title)){
				printMsg('post_title_required');
			}
			$row=$db->row_select_one("topics","id={$tid}");
			$postrow=$db->row_select_one("posts","tid={$tid} and istopic=1","id");
			
			if($row[userid]!=$lg[userid] && !isForumAdmin($fid)){
				printMsg('post_ownererr');
			}
			if($row['islock']==1 && !isForumAdmin($fid)){
				printMsg('post_islock');
			}

			$title=strFilter($_POST['title']);
			$content=strFilter($_POST['content']);
			$topic['title'] = $title;
			$topic['edittime'] = time();
			$topic['verifystate'] = (numFilter($forum['isneedverify'])>0?1:0);
			$db->row_update("topics",$topic,"id={$tid}");
			
			$post['title']=$title;
			$post['content'] = $content;
			$post['edittime'] = time();
			$post['verifystate'] = (numFilter($forum['isneedverify'])>0?1:0);
			$db->row_update("posts",$post,"tid={$tid} and istopic=1");
			
			checkAttachment($content, $tid, $postrow['id']);
			printMsg('post_edittopicsucceed');
		break;	
		
		//编辑回复
		case "editreply":
			$row=$db->row_select_one("posts","id={$postid} and istopic=0");
			if($row[userid]!=$lg[userid] && !isForumAdmin($fid)){
				printMsg('post_ownererr');
			}
			$post['title']=empty($title)?"{$row['title']}":$title;
			$post['content'] = $content;
			$post['edittime'] = time();
			$post['verifystate'] = (numFilter($forum['isneedverify'])==2?1:0);
			$db->row_update("posts",$post,"id={$postid}");
			checkAttachment($content, $row['tid'], $postid);
			printMsg('post_editreplysucceed');
		break;
	}
	
}else{
	require_once('header.php');
	require_once getTemplatePath('post.htm');
	footer();
}

function checkAttachment($content, $tid, $postid){
		$msglower=strtolower($content);
		if(strpos($msglower, '[/imgfile]') !== FALSE) {
			$content = preg_replace("/\s*\[imgfile\](\d+?)\[\/imgfile\]\s*/ies", "postParseFile('\\1','\\0', \$tid, \$postid, 'imgfile')", $content);
		}
		if(strpos($msglower, '[/file]') !== FALSE) {
			$content = preg_replace("/\s*\[file\](\d+?)\[\/file\]\s*/ies", "postParseFile('\\1','\\0', \$tid, \$postid, 'file')", $content);
		}
		global $hasImgAttach;
		global $hasCommonAttach;
		global $db;
		if($hasImgAttach){
			$topicrow['attachicon']='img';
			$db->row_update("topics",$topicrow,"id={$tid}");
		}
		elseif($hasCommonAttach){
			$topicrow['attachicon']='common';
			$db->row_update("topics",$topicrow,"id={$tid}");
		}
		return $content;
}

function postParseFile($s1, $s2, $tid, $postid, $filetype){
	global $lg;
	global $db;
	global $hasImgAttach;
	global $hasCommonAttach;
	$s1=numFilter($s1);
	$attach['tid']=$tid;
	$attach['postid']=$postid;
	$db->row_update("attachments",$attach,"id={$s1} and userid={$lg['userid']} and tid=0 and postid=0");
	if($db->affected_rows()>0){
		$hasImgAttach = ($filetype=='imgfile');
		$hasCommonAttach = ($filetype=='file');
	}
	updateCredits($lg['userid'], 'uploadvar');
}

function checkDirtyWords($content){
	global $db;
	$res=array();
	$res['doaction']=0;
	$rows = $db->row_select("dirtywords","type=0",0,"*","doaction");
	foreach($rows as $key=>$row){
		if(stristr($content,$row['word'])){
			if($row['doaction']==0){
				$content = str_replace($row['word'],$row['replaceto'],$content);
			}elseif($row['doaction']==1){
				$res['doaction']=1;
			}elseif($row['doaction']==2){
				$res['doaction']=2;
			}
		}
	}
	$res['content']=$content;
	return $res;
}
?>